/*
 * Copyright 2017 Baiyyy
 * @(#)NettyServerHandler.java
 */

package com.byyy.ccts.modules.cc.server;

import com.byyy.ccts.core.base.ILogBase;
import com.byyy.ccts.modules.cc.handle.IstrHandleInit;
import com.byyy.ccts.modules.cc.server.codec.CCTSServerProtocol;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 服务器接受客户端连接的动作处理
 * Created by DELL on 2018-4-26.
 */
@Service("cctsServerHandler")
@Sharable
public class CCTSServerHandler extends ChannelInboundHandlerAdapter implements ILogBase {

    @Autowired
    private IstrHandleInit istrHandleInit;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        CCTSServerProtocol protocol = (CCTSServerProtocol) msg;

        // 处理接收到的数据，采用责任链模式
        byte[] ret = istrHandleInit.getInstance().handleInstruction(protocol.getContent());
        if (ret != null && ret.length > 0) {
            protocol.setContent(ret);
            ctx.writeAndFlush(protocol);
        }
        // 因为设备是阻塞的，所以需要将命令结果发送完毕之后，才可以进行设备修改指令的发送
        ret = istrHandleInit.getInstance().afterHandle(protocol.getContent());
        if (ret != null && ret.length > 0) {
            protocol.setContent(ret);
            ctx.writeAndFlush(protocol);
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error(cause.getMessage(), cause);
        ctx.close();
    }

}
